import urllib

from baseHandler import PayHandler, http_result, Application, init_logger
import asyncio
import json
from tornado import gen
import logging
logger = init_logger("alipay", "/data/log/alipay/alipay.log", level=logging.DEBUG)


class Aliapyb2cHandler(PayHandler):
    @gen.coroutine
    def post(self):
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write({"message": "商户不存在", "ret": -1})
        if not self.check_ip():
            return self.write({"message": "ip错误", "ret": -1})
        if not self.check_sign():
            logger.info("签名验证失败")
            return self.write({"message": "签名验证失败", "ret": -1})
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        logger.debug(data)

        # 检查data 数据
        if "ordernumber" not in data:
            return self.write({"message": "缺少ordernumber订单号", "ret": -1})
        if "amount" not in data:
            return self.write({"message": "缺少amount交易金额", "ret": -1})
        if "backurl" not in data:
            return self.write({"message": "缺少backurl后台通知地址", "ret": -1})
        if "body" not in data:
            return self.write({"message": "缺少body订单描述", "ret": -1})
        if "authcode" not in data:
            return self.write({"message": "缺少authcode授权码", "ret": -1})
        logger.info("%s|支付宝b2c|订单%s|金额%s", self.merchantid, data["ordernumber"], data['amount'])

        input_json = {
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCTYPE": "MPAY",
            "FUNCCODE": "100201",
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "REQINFO": {
                "MERCHANTID": str(self.merchantid),
                "MERCHANTORDERNO": str(data["ordernumber"]),
                "OPMONEY": str(data["amount"]),
                "BIZID": "PAY.ALIPAY.B2C",
                "NOTIFYURL": data["backurl"],
                "RETURNURL": "",
                "GOODSNAME": data["body"],
                "CLIENTIP": self.remote_ip,
                "PAYSOURE": "CP01",
                "AUTHCODE": data["authcode"]
            }
        }
        logger.debug(input_json)
        core_response = yield from self.pay_core('PAY_ALIPAY_B2C_REQ', input_json)
        logger.info(core_response)
        if core_response['RETREDIRECT'] == "PAY.CORE.EBS":
            logger.info('%s|支付宝b2c|订单%s|-1|%s', self.merchantid, data["ordernumber"], core_response["MESSAGE"])
            return self.write({"ret": -1, "message": core_response["MESSAGE"]})
        else:
            channel = yield self.get_channel_redis(core_response['PAYCHANNEL'])
            logger.info(channel)
            request_obj = {
                "CFGPARA": core_response["CFGPARA"],
                "OPMONEY": core_response["OPMONEY"],
                "OUTERORDERNO": core_response["OUTERORDERNO"],
                "PAYCHANNEL": core_response["PAYCHANNEL"],
                "AUTHCODE": data["authcode"],
                "BODY": data["body"],
                "mer_no": data.get("mer_no"),
                "key": data.get("key")
            }
            # 发送到渠道
            response = yield http_result(channel, request_obj)
            logger.debug(response.body)
            if response.code == 200 and response.body.startswith(b'{'):
                channel_result = json.loads(response.body.decode("utf-8"))
                orderstate = channel_result.get("respcode") or channel_result.get("orderstate")
                logger.info('%s|支付宝b2c|订单%s|支付结果%s', self.merchantid, data['ordernumber'], orderstate)

            else:
                orderstate = "1"
                message = response.body.decode('utf-8')
                channel_result = {"payorderid": message}
                logger.info('%s|支付宝b2c|订单%s|支付结果%s|%s', self.merchantid, data['ordernumber'], orderstate, message)

            input_json = {
                "DEPTID": "800001",
                "OPERID": "9527",
                "FUNCTYPE": "RESP",
                "FUNCCODE": "100202",
                "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
                "REQINFO": {
                    "OUTERORDERNO": core_response["OUTERORDERNO"],
                    "OPMONEY": str(core_response["OPMONEY"]),
                    # "PAYORDERNO": payorderid,
                    "ORDERSTATE": orderstate,
                    "PAYINFO": channel_result.get('payorderid') or "none",
                }
            }
            logger.debug(input_json)
            result = yield from self.pay_core("PAY_ALIPAY_B2C_RES", input_json)
            logger.debug(result)
            result.update({"MERCHANTID": self.merchantid})
            if result["MESSAGE"] == 'SUCCESS':
                rsp_obj = {
                    "payinfo": result['PAYINFO'],
                    "payorderno": result["OUTERORDERNO"],
                    "body": data["body"],
                    "amount": result["OPMONEY"],
                    "businesstime": result['RESPTIME'],
                    "orderstate": orderstate
                }
                return_data = self.niti_data(rsp_obj, result)
                return_data.update({"ret": 0, 'message': "success"})
                return self.write(return_data)
            else:
                return self.write({"ret": -1, "message": result['MESSAGE']})


class Aliapyc2bHandler(PayHandler):
    @gen.coroutine
    def get(self):
        # 检查商户
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write(json.dumps({"message": "商户不存在", "ret": -1}))
        if not self.check_ip():
            return self.write(json.dumps({"message": "ip错误", "ret": -1}))
        if not self.check_sign():
            logger.info("%s 签名验证失败", self.merchantid)
            return self.write(json.dumps({"message": "签名验证失败", "ret": -1}))
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        # 检查data 数据

        res = self.check_ordernumber(data)
        if res:
            return self.write(res)
        if "amount" not in data:
            return self.write({"message": "缺少amount交易金额", "ret": -1})
        if "backurl" not in data:
            return self.write({"message": "缺少backurl后台通知地址", "ret": -1})
        if "body" not in data:
            return self.write({"message": "缺少body订单描述", "ret": -1})
        logger.info("%s|支付宝c2b|订单%s|金额%s", self.merchantid, data["ordernumber"], data['amount'])
        if len(data["ordernumber"]) > 32:
            return self.write({"message": "订单号长度错误", "ret": -1})
        if not str(data["amount"]).isdigit():
            return self.write({"message": "金额错误", "ret": -1})
        if len(data["body"]) > 128:
            return self.write({"message": "订单描述长度错误", "ret": -1})
        pieces = urllib.parse.urlparse(data["backurl"])
        if not all([pieces.scheme, pieces.netloc]) or pieces.scheme not in ['http', 'https']:
            return self.write({"message": "backurl 格式错误", "ret": -1})
        # 发动给核心后台

        biz_id = 'PAY.ALIPAY.C2B'
        input_json = {
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCTYPE": "MPAY",
            "FUNCCODE": "100201",
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "REQINFO": {
                "MERCHANTID": str(self.merchantid),
                "MERCHANTORDERNO": str(data["ordernumber"]),
                "OPMONEY": str(data["amount"]),
                "BIZID": biz_id,
                "NOTIFYURL": data["backurl"],
                "RETURNURL": "",
                "GOODSNAME": data["body"],
                "CLIENTIP": self.remote_ip,
                "PAYSOURE": "CP01"
            }
        }
        logger.info(input_json)
        core_response = yield from self.pay_core('PAY_ALIPAY_C2B_REQ', input_json)
        logger.info(core_response)
        if core_response['RETREDIRECT'] == "PAY.CORE.EBS":
            logger.info('%s|支付宝c2b|订单%s|-1|%s', self.merchantid, data["ordernumber"], core_response["MESSAGE"])
            return self.write({"ret": -1, "message": core_response["MESSAGE"]})
        else:
            channel = yield self.get_channel_redis(core_response['PAYCHANNEL'])
            request_obj = {
                "CFGPARA": core_response["CFGPARA"],
                "OPMONEY": core_response["OPMONEY"],
                "OUTERORDERNO": core_response["OUTERORDERNO"],
                "PAYCHANNEL": core_response["PAYCHANNEL"],
                "BODY": data["body"]
            }
            # 发送到渠道
            qrcode = ""
            payorderid = ""
            payinfo = ""
            response = yield http_result(channel, request_obj)
            # logger.info(response.body)
            if response.code == 200 and response.body.startswith(b'{'):
                channel_result = json.loads(response.body.decode("utf-8"))
                # logger.info(channel_result)
                orderstate = channel_result.get("respcode")
                qrcode = channel_result.get("qrcode", "")
                payorderid = channel_result.get("payorderid", "")
                payinfo = channel_result.get('payinfo') or channel_result.get('message')
                logger.info("%s|支付宝c2b|订单%s|支付结果%s", self.merchantid, data["ordernumber"], orderstate)
            else:
                orderstate = "1"
                logger.info('%s|支付宝b2c|订单%s|支付结果%s|%s', self.merchantid, data['ordernumber'], orderstate, qrcode)
            input_json = {
                "DEPTID": "800001",
                "OPERID": "9527",
                "FUNCTYPE": "RESP",
                "FUNCCODE": "100202",
                "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
                "REQINFO": {
                    "OUTERORDERNO": core_response["OUTERORDERNO"],
                    "OPMONEY": str(core_response["OPMONEY"]),
                    "PAYORDERNO": payorderid or core_response["OUTERORDERNO"],
                    "ORDERSTATE": orderstate,
                    "PAYINFO": qrcode or core_response["OUTERORDERNO"]
                }
            }
            logger.info(input_json)
            result = yield from self.pay_core("PAY_ALIPAY_C2B_RES", input_json)
            logger.info(result)
            # qrcode = result.get("PAYINFO", "")
            # result.update({"MERCHANTID": self.merchantid})
            # if qrcode:
            # return_data = self.niti_data({"payinfo": payinfo, "qrcode": qrcode, "orderstate": orderstate}, result)

            # return_data.update({"ret": int(orderstate), 'message': "success"})
            return self.write(payinfo)

    @gen.coroutine
    def post(self):
        # 检查商户
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write(json.dumps({"message": "商户不存在", "ret": -1}))
        if not self.check_ip():
            return self.write(json.dumps({"message": "ip错误", "ret": -1}))
        if not self.check_sign():
            logger.info("%s 签名验证失败", self.merchantid)
            return self.write(json.dumps({"message": "签名验证失败", "ret": -1}))
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        # 检查data 数据

        res = self.check_ordernumber(data)
        if res:
            return self.write(res)
        if "amount" not in data:
            return self.write({"message": "缺少amount交易金额", "ret": -1})
        if "backurl" not in data:
            return self.write({"message": "缺少backurl后台通知地址", "ret": -1})
        if "body" not in data:
            return self.write({"message": "缺少body订单描述", "ret": -1})
        logger.info("%s|支付宝c2b|订单%s|金额%s", self.merchantid, data["ordernumber"], data['amount'])
        if len(data["ordernumber"]) > 32:
            return self.write({"message": "订单号长度错误", "ret": -1})
        if not str(data["amount"]).isdigit():
            return self.write({"message": "金额错误", "ret": -1})
        if len(data["body"]) > 128:
            return self.write({"message": "订单描述长度错误", "ret": -1})
        pieces = urllib.parse.urlparse(data["backurl"])
        if not all([pieces.scheme, pieces.netloc]) or pieces.scheme not in ['http', 'https']:
            return self.write({"message": "backurl 格式错误", "ret": -1})
        # 发动给核心后台

        biz_id = "PAY.ALIPAY.C2B"
        input_json = {
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCTYPE": "MPAY",
            "FUNCCODE": "100201",
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "REQINFO": {
                "MERCHANTID": str(self.merchantid),
                "MERCHANTORDERNO": str(data["ordernumber"]),
                "OPMONEY": str(data["amount"]),
                "BIZID":  biz_id,
                "NOTIFYURL": data["backurl"],
                "RETURNURL": "",
                "GOODSNAME": data["body"],
                "CLIENTIP": self.remote_ip,
                "PAYSOURE": "CP01"
            }
        }
        logger.info(input_json)
        core_response = yield from self.pay_core('PAY_ALIPAY_C2B_REQ', input_json)
        logger.info(core_response)
        if core_response['RETREDIRECT'] == "PAY.CORE.EBS":
            logger.info('%s|支付宝c2b|订单%s|-1|%s', self.merchantid, data["ordernumber"], core_response["MESSAGE"])
            return self.write({"ret": -1, "message": core_response["MESSAGE"]})
        else:
            channel = yield self.get_channel_redis(core_response['PAYCHANNEL'])
            request_obj = {
                "CFGPARA": core_response["CFGPARA"],
                "OPMONEY": core_response["OPMONEY"],
                "OUTERORDERNO": core_response["OUTERORDERNO"],
                "PAYCHANNEL": core_response["PAYCHANNEL"],
                "BODY": data["body"]
            }
            # 发送到渠道
            qrcode = ""
            payorderid = ""
            payinfo = ""
            message = ""
            response = yield http_result(channel, request_obj)
            if response.code == 200 and response.body.startswith(b'{'):
                channel_result = json.loads(response.body.decode("utf-8"))
                # logger.info(channel_result)
                orderstate = channel_result.get("respcode")
                qrcode = channel_result.get("qrcode", "")
                payorderid = channel_result.get("payorderid", "")
                payinfo = channel_result.get('payinfo', "")
                message = channel_result.get('message', "")
                logger.info("%s|支付宝c2b|订单%s|支付结果%s", self.merchantid, data["ordernumber"], orderstate)
            else:
                orderstate = "1"
                logger.info('%s|支付宝b2c|订单%s|支付结果%s|%s', self.merchantid, data['ordernumber'], orderstate, qrcode)
            input_json = {
                "DEPTID": "800001",
                "OPERID": "9527",
                "FUNCTYPE": "RESP",
                "FUNCCODE": "100202",
                "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
                "REQINFO": {
                    "OUTERORDERNO": core_response["OUTERORDERNO"],
                    "OPMONEY": str(core_response["OPMONEY"]),
                    "PAYORDERNO": payorderid or core_response["OUTERORDERNO"],
                    "ORDERSTATE": str(orderstate),
                    "PAYINFO": qrcode or core_response["OUTERORDERNO"]
                }
            }
            logger.info(input_json)
            result = yield from self.pay_core("PAY_ALIPAY_C2B_RES", input_json)
            logger.info(result)
            # qrcode = result.get("PAYINFO", "")
            result.update({"MERCHANTID": self.merchantid})
            # if qrcode:
            return_data = self.niti_data({"payinfo": payinfo, "qrcode": qrcode, "orderstate": orderstate, 'message': message }, result)

            return_data.update({"ret": int(orderstate), 'message': "success"})
            return self.write(return_data)
            # else:
            #     return self.write({"ret": -1, "message": "failed"})


class AliapyQueryHandler(PayHandler):
    @gen.coroutine
    def post(self):
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write(json.dumps({"message": "商户不存在", "ret": -1}))
        if not self.check_ip():
            return self.write(json.dumps({"message": "ip错误", "ret": -1}))
        if not self.check_sign():
            logger.info("签名验证失败")
            return self.write(json.dumps({"message": "签名验证失败", "ret": -1}))
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        ordernumber = data['ordernumber']
        logger.info("%s|支付宝查询|订单号%s", self.merchantid, ordernumber)
        input_json = {
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "FUNCTYPE": "QUER",
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCCODE": "100202",
            "REQINFO": {
                "MERCHANTORDERNO": ordernumber,
                "MERCHANTID": self.merchantid
            }
        }
        result = yield from self.pay_core("PAY_ORDER_QUERY", input_json)
        logger.info(result)
        if result["RETREDIRECT"] == "PAY.CORE.EBS" and result["MESSAGE"] == "SUCCESS":
            obj = {
                "ordernumber": result["MERCHANTORDERNO"],
                "amount": result["AMOUNT"],
                "payorderid": result["OUTERORDERNO"],
                "paystate": result["PAYSTATE"],
                "businesstime": result["RESPTIME"]

            }
            return_obj = self.niti_data(obj, result)
            return_obj.update({"ret": 0, "message": "success"})

            return self.write(return_obj)
        else:
            return self.write({"ret": "-1", "message": result["MESSAGE"]})


class QueryHandler(PayHandler):
    @gen.coroutine
    def post(self):
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write(json.dumps({"message": "商户不存在", "ret": -1}))
        if not self.check_ip():
            return self.write(json.dumps({"message": "ip错误", "ret": -1}))
        if not self.check_sign():
            logger.info("签名验证失败")
            return self.write(json.dumps({"message": "签名验证失败", "ret": -1}))
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        ordernumber = data['ordernumber']
        logger.info("%s|查询|订单号%s", self.merchantid, ordernumber)
        input_json = {
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "FUNCTYPE": "QUER",
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCCODE": "100202",
            "REQINFO": {
                "MERCHANTORDERNO": ordernumber,
                "MERCHANTID": self.merchantid
            }
        }
        core_response = yield from self.pay_core("PAY_ORDER_QUERY", input_json)
        logger.info(core_response)
        if core_response["RESPCODE"] not in ("10000000", "1000000"):
            return self.write({"ret": -1, "message": core_response["MESSAGE"]})

        if core_response['PAYSTATE'] in ("0", "1"):
            obj = {
                "payorderid": core_response["OUTERORDERNO"],
                "amount": core_response["AMOUNT"],
                # "c": result["OUTERORDERNO"],
                "orderstate": core_response["RESPCODE"],
                "businesstime": core_response["RESPTIME"]
            }
            return_obj = self.niti_data(obj, core_response)
            return_obj.update({"ret": 0, "message": "success"})

            return self.write(return_obj)

        channel = core_response.get("PAY_CHANNEL", "")
        logger.info(channel)
        url = yield self.get_channel_redis(channel + '_Q')
        if not url:
            return self.write({"ret": -1, "message": "未知错误"})

        core_response['CFGPARA'] = json.loads(core_response['PAY_CFG_JSON'])
        response = yield http_result(url, core_response)
        logger.info(response.body)
        if response.code == 200 and response.body.startswith(b'{'):
            channel_result = json.loads(response.body.decode("utf-8"))
            orderstate = channel_result["respcode"]
            logger.info('%s|支付宝查询|订单%s|支付结果%s', self.merchantid, data['ordernumber'], orderstate)
        else:
            orderstate = "8"
            if response.code == 200:
                message = response.body.decode('utf-8')
            else:
                message = '500%s' % response.code
            channel_result = {"message": message}
            logger.info('%s|支付宝查询|订单%s|支付结果%s|%s', self.merchantid, data['ordernumber'], orderstate, message)

        input_json = {
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCTYPE": "NOTI",
            "FUNCCODE": "100201",
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "REQINFO": {
                'OUTERORDERNO': core_response["OUTERORDERNO"],
                "ORDERSTATE": orderstate,
                "OPMONEY": str(core_response["AMOUNT"]),
                "NOTIFYINFO": channel_result.get('payorderid') or "None",
            }
        }
        # 发送到核心程序
        logger.info(input_json)
        result = yield from self.pay_core("PAY_ALIPAY_NOTIFY", input_json)
        logger.info(result)

        obj = {
            "payorderid":  core_response["OUTERORDERNO"],
            "amount": core_response["AMOUNT"],
            # "c": result["OUTERORDERNO"],
            "orderstate":  orderstate,
            "businesstime": core_response["RESPTIME"]
        }
        return_obj = self.niti_data(obj, core_response)
        return_obj.update({"ret": 0, "message": "success"})

        self.write(return_obj)
        self.finish()

        # notifyurl = result.get("NOTIFIYURL", "")
        # if notifyurl:
        #     merchantid = core_response.get("MERCHANTID")
        #     res = yield self.merchant_exit(merchantid=merchantid)
        #     for i in range(5):
        #         notify_data = {
        #             "ordernumber": result["MERCHANTORDERNO"],
        #             "respcode": result["ORDERSTATE"],
        #             "merchantid": merchantid,
        #             "amount": result["OPMONEY"],
        #             "businesstime": result["RESPTIME"]
        #         }
        #
        #         request_obj = self.niti_data(notify_data, result)
        #         rsp = yield http_result(notifyurl, request_obj, model='urlencode')
        #         logger.info(rsp.body)
        #         # content = rsp.body.upper()
        #         if rsp.code == 200 and rsp.body in (b'SUCCESS', b'success'):
        #             logger.info("%s|%s收到下游成功应答|订单号%s", i, data["out_trade_no"], result["MERCHANTORDERNO"])
        #             noti = yield from self.pay_core("PAY_ALIPAY_NOTIFY_RES", {
        #                 "REQINFO": {"MERCHANTID": merchantid, "MERCHANTORDERNO": result["MERCHANTORDERNO"]}})
        #             logger.debug(noti)
        #             break
        #         else:
        #             logger.info("%s|%s未收到下游成功应答|订单号%s", i, data["out_trade_no"], result["MERCHANTORDERNO"])
        #             yield from asyncio.sleep(10 * (i + 1))





class AliapyClosedHandler(PayHandler):
    @gen.coroutine
    def post(self):
        exited = yield self.merchant_exit()
        if not exited:
            logger.info("商户不存在")
            return self.write(json.dumps({"message": "商户不存在", "ret": -1}))
        if not self.check_ip():
            return self.write(json.dumps({"message": "ip错误", "ret": -1}))
        if not self.check_sign():
            logger.info("签名验证失败")
            return self.write(json.dumps({"message": "签名验证失败", "ret": -1}))
        data = self.decrypt()
        if not data:
            return self.write({"message": "解密失败", "ret": -1})
        data = json.loads(data)
        ordernumber = data['ordernumber']
        logger.info('%s|支付宝订单关闭|订单号%s', self.merchantid, ordernumber)
        input_json = {
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "FUNCTYPE": "CLOS",
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCCODE": "100202",
            "REQINFO": {
                "MERCHANTORDERNO": ordernumber,
                "MERCHANTID": self.merchantid
            }
        }
        result = yield from self.pay_core("PAY_ORDER_CLOSE", input_json)
        if result["RETREDIRECT"] == "PAY.CORE.EBS" and result["MESSAGE"] == "SUCCESS":
            obj = {
                "closetime": result["CLOSETIME"]
            }
            result["RESPTIME"] = result["CLOSETIME"]
            return_obj = self.niti_data(obj, result)
            return_obj.update({"ret": 0, "message": "success"})

            return self.write(return_obj)
        logger.warn('订单%s|关闭失败[%s]', ordernumber, result["MESSAGE"])
        return self.write({"ret": -1, "message": result["MESSAGE"]})


if __name__ == "__main__":
    handlers = [
        # (r'/pay/alipay/c2b', Aliapyc2bHandler),
        (r'/pay/alipay/b2c', Aliapyb2cHandler),
        (r'/pay/alipay/h5', Aliapyc2bHandler),
        (r'/pay/alipay/queryorder/?', QueryHandler),
        (r'/pay/alipay/closed', AliapyClosedHandler),
    ]

    logger.info("Run alipay server ... http://127.0.0.1:9998")
    application = Application(handlers, debug=False)
    application.listen(9998, address="127.0.0.1")

    loop = asyncio.get_event_loop()
    application.init_with_loop(loop)
    loop.run_forever()
